<?php
/**
 * 名称：GoodsAction
 * 描述：后台商品管理
 * 作者：jepin 时间：2014-07-30
 * 版本号：V1.0.0
 */
class GoodsAction extends CommonAction {
	/**
	 * 得到商品列表
	 */
	public function goodsList(){
		import("ORG.Util.Page"); // 导入分页类
		if($_GET['name'] != null && $_GET['name'] != "" ){
			$map['name'] = array("like","%".$_GET['name']."%");
			$this->assign("name",$_GET['name']);
			$this->assign("search","yes");
		}
		if($_GET['cate_id'] != null && $_GET['cate_id'] != "" ){
			$map['cate_id'] = intval($_GET['cate_id']);
			$this->assign("cate_id",$_GET['cate_id']);
			$this->assign("search","yes");
		}
		if($_GET['status'] != null && $_GET['status'] != "" ){
			if(intval($_GET['status']) == 4){
				$map['is_del'] = array('neq',1);
			}else {
				$map['is_del'] = intval($_GET['status']);
			}
			$this->assign("status",$_GET['status']);
			$this->assign("search","yes");
		}else{
			$map['is_del'] = array('neq',1);
			$this->assign("status",'4');
			$this->assign("search","yes");
		}
		$item_cate = model('GoodsCate')->select();
		$this->assign("item_cate",$item_cate);
		$count = model('Goods') -> where($map)->count();
		$page = new Page($count,20);
		$data = model('Goods')  -> where($map) -> order('id,cate_id') -> limit($page->firstRow . ',' . $page->listRows)->select();
		// 将分类信息加入列表显示
		foreach ($data as $k=>$v){
			$images = (unserialize($data[$k]['imgs'])); 
			$data[$k]['imgs'] =$images[0];
			if( $data[$k]['cate_id']== 0){
				$data[$k]['cate_name'] = '未分类';
			}else{
				$data[$k]['cate_name'] = model('GoodsCate')->getCateNameByID($data[$k]['cate_id']);
			}
		}
		$show = $page->show(); // 分页显示输出
		$this->assign('page', $show); // 赋值分页输出
		$this->assign('data', $data);
		$this->display();
	}
	
	/**
	 * 商品下架 
	 */
    public function doDownGoods(){
    	if($_POST['ids'] == null || $_POST['ids'] == "" ){
    		echo 0;
    		exit();
    	}
    	$ids = $_POST['ids'];
    	$res = M()->query(" UPDATE  ".C('DB_PREFIX')."goods SET is_del = 2 where `id` in (".$ids.")");
    	//$res = model('Goods') -> where("`id` in (".$ids.")") -> delete();
    	//echo $res ? 1 : 0;
    	echo 1;
    }
	
    /**
     * 商品上架
     */
    public function doUpGoods(){
    	if($_POST['ids'] == null || $_POST['ids'] == "" ){
    		echo 0;
    		exit();
    	}
    	$ids = $_POST['ids'];
    	M()->query(" UPDATE  ".C('DB_PREFIX')."goods SET is_del = 0 where `id` in (".$ids.")");
    	echo 1;
    }
    
    
	/**
	 * 新增与修改商品
	 */
	public function addGoods(){
		if(!empty($_GET['id'])){
		  $id  = intval($_GET['id']) ;
		  $goods= model('Goods')->getGoodsByID($id);
		  $goods['imgs'] = unserialize($goods['imgs']);
		  $this->assign('goods',$goods);	
		}
		$item_cate = model('GoodsCate')->select();
		$this->assign("item_cate",$item_cate);
 		$this->display();
	}
	
	/**
	 * 删除商品
	 */
	public function doDeleteGoods(){
        //  逻辑删除商品
		if($_POST['ids'] == null || $_POST['ids'] == "" ){
			echo 0;
			exit();
		}
		$ids = $_POST['ids'];
		M()->query(" UPDATE  ".C('DB_PREFIX')."goods SET is_del = 1 where `id` in (".$ids.")");
		echo  1;
	}
	
	/**
	 * 永久删除商品
	 */
	public function doDelGoods(){
		if($_POST['ids'] == null || $_POST['ids'] == "" ){
			echo 0;
			exit();
		}
		$ids = $_POST['ids'];
		$idlist = explode(',',$ids);
		//移除图片动作
		foreach($idlist as $id){
			$goods = model('Goods')->find($id);
		    $imgs  = unserialize($goods['imgs']);
		    foreach ($imgs as $img){
		       $img = SITE_PATH.$img;
		        if(file_exists($img)){
 		           unlink($img);     //  移除图片
	   	        }  
		    }
		}
	    $res = M('Goods')->where('id in ('.$ids.')')->delete();
		echo $res? 1:0;
	}
	
	/**
	 * 新增商品
	 */
	public function doaddGoods(){
		if (!empty($_POST['id'])){
		    $data['id']    = intval($_POST['id']);
		}
		$data['name']            = $_POST['name'];
		$data['num']             = $_POST['num'];
		$data['price']           = $_POST['price'];
		$data['imgs']            = serialize($_POST['imgs']);
		$data['detail_url']      = $_POST['detail_url'];
		$data['desc']            = $_POST['desc'];
		$data['created']         = time();
		$data['cate_id']         = $_POST['cate_id'];
		$data['user_id']         = intval($data['user_id']);
		$userinfo                = model('User')->getUserByIdentifier($this->mid);
		$data['username']        = $userinfo['uname'];
	    $data['is_del']          = $_POST['is_del'];
		$result = model('Goods')->addGoods($data);
		if(!empty($_POST['del_imgs'])){
			$del_imgs  = $_POST['del_imgs'];
			foreach($del_imgs as  $del_img){
				$this->removePic($del_img);
			}
		}
		if($result){
			$this->success("操作成功",URL('admin/Goods/goodsList',array('status'=>$_POST['is_del'])));
		}else{
			$this->error('操作失败');
		}
	}
	
	/**
	 * 文件上传动作
	 */
	public function uploadFile(){
		$picSavePath ='./data/goods/upload';
		$picSavePath = substr($picSavePath,2,strlen($picSavePath)).'/';
		$save_path = SITE_PATH.'/'.$picSavePath;
		if (!file_exists($save_path)) {
			mk_dir($save_path);
		}
		 $this->uploadPic($save_path,$picSavePath);
	}
	
	/**
	 * kindeditor图片、视频、swf上传
	 * @param string $save_path 图片保存路径
	 * @param string $save_url 文件保存目录URL
	 */
    public function uploadPic($save_path,$save_url,$dirname, $saveFileName=true) {
		if (!file_exists($save_path)) {
			mk_dir($save_path);
		}
		$php_url = './';
		$save_url = $php_url .$save_url;
		//定义允许上传的文件扩展名
		$ext_arr = array(
				'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
				'flash' => array('swf', 'flv'),
				'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
				'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
		);
		//最大文件大小
		$max_size = 10000000;
		$save_path = realpath($save_path) . '/';
		//PHP上传失败
		if (!empty($_FILES['imgFile']['error'])) {
			switch($_FILES['imgFile']['error']){
				case '1':
					$error = '超过php.ini允许的大小。';
					break;
				case '2':
					$error = '超过表单允许的大小。';
					break;
				case '3':
					$error = '图片只有部分被上传。';
					break;
				case '4':
					$error = '请选择图片。';
					break;
				case '6':
					$error = '找不到临时目录。';
					break;
				case '7':
					$error = '写文件到硬盘出错。';
					break;
				case '8':
					$error = 'File upload stopped by extension。';
					break;
				case '999':
				default:
					$error = '未知错误。';
			}
			echo json_encode(array('error' => 1, 'message' => $error));
			exit;
		}
		//有上传文件时
		if (empty($_FILES) === false) {
			//原文件名
			$file_name = $_FILES['imgFile']['name'];
			//服务器上临时文件名
			$tmp_name = $_FILES['imgFile']['tmp_name'];
			//文件大小
			$file_size = $_FILES['imgFile']['size'];
			//检查文件名
			if (!$file_name) {
				echo json_encode(array('error' => 1, 'message' => "请选择文件。"));
				exit;
			}
			//检查目录
			if (@is_dir($save_path) === false) {
				echo json_encode(array('error' => 1, 'message' => "上传目录不存在。"));
				exit;
			}
			//检查目录写权限
			if (@is_writable($save_path) === false) {
				echo json_encode(array('error' => 1, 'message' => "上传目录没有写权限。"));
				exit;
			}
			//检查是否已上传
			if (@is_uploaded_file($tmp_name) === false) {
				echo json_encode(array('error' => 1, 'message' => "上传失败。"));
				exit;
			}
			//检查文件大小
			if ($file_size > $max_size) {
				echo json_encode(array('error' => 1, 'message' => "上传文件大小超过限制。"));
				exit;
			}
			//获得文件扩展名
			$temp_arr = explode(".", $file_name);
			$file_ext = array_pop($temp_arr);
			$file_ext = trim($file_ext);
			$file_ext = strtolower($file_ext);
			//检查目录名
			if(!empty($dirname))
				$dir_name = $dirname;
			else {
				if ($saveFileName) {
					$dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
					if (empty($ext_arr[$dir_name])) {
						echo json_encode(array('error' => 1, 'message' => "目录名不正确。"));
						exit;
					}
					//检查扩展名
					if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
						echo json_encode(array('error' => 1, 'message' => "上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。"));
						exit;
					}
				}
			}
		 
			$configfilepath='/apps/cms/Conf/yunconfig.php';
			$isopenyun = service("Xattach") -> isOpenYun($configfilepath);
			if($isopenyun){
				$file_url = service("Xattach") -> uploadUpYun($dir_name,$configfilepath);
				if($file_url === false){
					echo json_encode(array('error' => 1, 'message' => "上传文件失败。"));
					exit;
				}
			}else{
				//创建文件夹
				if ($dir_name !== '') {
					$save_path .= $dir_name . "/";
					$save_url .= $dir_name . "/";
					if (!file_exists($save_path)) {
						mkdir($save_path);
					}
				}
				if ($saveFileName) {
					$ymd = date("Ymd");
					$save_path .= $ymd . "/";
					$save_url .= $ymd . "/";
					if (!file_exists($save_path)) {
						mkdir($save_path);
					}
					//新文件名
					$new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
				} else {
					$new_file_name = 'templatePic.'.$file_ext;
				}
	
				//移动文件
				$file_path = $save_path . $new_file_name;
				if (move_uploaded_file($tmp_name, $file_path) === false) {
					echo json_encode(array('error' => 1, 'message' => "上传文件失败。"));
					exit;
				}
				@chmod($file_path, 0644);
				if ($saveFileName) {
					$file_url = $save_url . $new_file_name;
				} else {
					$file_url = $new_file_name;
				}
			}
			header('Content-type: text/html; charset=UTF-8');
			echo json_encode(array('error' => 0, 'url' => $file_url));
			exit;
		}
	}
	
	/**
	 * 上传互联网图片
	 */
	function getImage($url, $filename='', $dirName, $fileType, $type=0)
	{
		if($url == ''){return false;}
		//获取文件原文件名
		$defaultFileName = basename($url);
		//获取文件类型
		$suffix = substr(strrchr($url,'.'), 1);
		if(!in_array($suffix, $fileType)){
			return false;
		}
		//设置保存后的文件名
		$filename = $filename == '' ? time().rand(0,9).'.'.$suffix : $defaultFileName;
	
		//获取远程文件资源
		if($type){
			$ch = curl_init();
			$timeout = 5;
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$file = curl_exec($ch);
			curl_close($ch);
		}else{
			ob_start();
			readfile($url);
			$file = ob_get_contents();
			ob_end_clean();
		}
		//设置文件保存路径
		$ymd = date("Ymd");
		$dirName = './'.$dirName.'/image/'.$ymd.'/';
		if(!file_exists($dirName)){
			mkdir(SITE_PATH.'/'.$dirName, 0777, true);
		}
		//保存文件
		$res = fopen(SITE_PATH.'/'.$dirName.$filename,'a');
		fwrite($res,$file);
		fclose($res);
		return  $dirName.$filename;
	}
	
	/**
	 * 根据链接  下载图片
	 * @param  图片的互联网地址
	 */
	function uploadUrlPic($url){
		$picSavePath ='./data/goods/upload';
		$picSavePath = substr($picSavePath,2,strlen($picSavePath)).'/';
	    return   $this->getImage($url, '', $picSavePath, array('jpg', 'gif'));
	}
	
	/**
	 * 移除图片
	 * @param  $pic_url 本地图片地址
	 */
	public function removePic($pic_url){
		$pic_url =SITE_PATH.$pic_url;
		if(file_exists($pic_url)){
			$result = unlink($pic_url);
			echo '1';
		}else{
			echo '0';
		}
	}
	
	/**
	 * 商品接口管理  ：显示列表 
	 */
	function itemSite(){
	   $data = model('ItemSite')->select();
	   $this->assign('data',$data);
	   $this->display();	
	}
	/**
	 * 新增商品接口
	 */
	function addItemSite(){
		$id = $_GET['id'];
		if(!empty($id)){
			$id =intval($_GET['id']);
			$itemsite = model('ItemSite')->find($id);
			$this->assign('itemsite',$itemsite);
		}
		$this->display();
	}
	
	/**
	 * 增加商品接口动作
	 */
	function doAddItemSite(){
		if(!empty( $_POST['id'])){
			$data['id'] = intval($_POST['id']);
		}
		$data['name']   = $_POST['name'];     // 名称
		$data['domain'] = $_POST['domain'];   // 一级域名
		$data['url']    = $_POST['url'];      // 对应的地址
		$data['desc']   = $_POST['desc'];     // 描述
		$data['code']   = $_POST['code'];     // 操控码 如 taobao  则调用的是淘宝接口
		$data['appkey'] = $_POST['appkey'];   // appkey
		$data['secret'] = $_POST['secret'];   // secret
		$data['status'] = $_POST['status'];   // 状态  开启和关闭  
		$result = model('ItemSite')->addItemSite($data);
		if($result){
			$this->success("操作成功",URL('admin/Goods/itemSite'));
		}else{
			$this->error("新增失败");
		}
	}
	
	/**
	 * 删除商品接口
	 */
	function doDelItemSite(){
		if($_POST['ids'] == null || $_POST['ids'] == "" ){
			echo 0;
			exit();
		}
		$ids = $_POST['ids'];
		$res = model('ItemSite') -> where("`id` in (".$ids.")") -> delete();
		echo $res ? 1 : 0;
	}
	
	/**
	 * 通过导入淘宝商品信息
	 * 
	 */
	function inportGoods(){
		$this->display();
	}
	
	/**
	 * 导入淘宝商品信息实现
	 */
    function doImportGoods(){
        $url_list = $_POST['url_list'];
    	$url_list = split(PHP_EOL, $url_list);
    	$item_mod = model('Goods');
    	$flag = true;
    	import('@.ORG.itemcollect','','.class.php');
    	foreach ($url_list as $url) {
    		if (!$url) continue;
    		//获取商品信息
    		$itemcollect = new itemcollect();
    		$itemcollect->url_parse($url);
    		$t_id = $itemcollect->get_id();
    		if (model('Goods')->isExist($t_id)){
    			continue;
    		}
    		$item = $itemcollect->fetch();
    		if(!$item)  {
    			$flag = false;
    			continue;
    		}
    		$data['name']           = $item['title'];
    		$data['num']            = 0;
    		$data['price']          = $item['price'];
    		$data['created']        = time();
    		$data['is_del']         = 3;
    		$data['desc']           = $item['sell_point'];
    		$data['detail_url']     = $url;
    		$data['num_iid']        = $t_id;
    		
    		// 图片处理
    		$item_imgs = (array)$item["item_imgs"];
    		$imaglist  = (array)$item_imgs['item_img']; 
    		$i = 0;
    		$imageinfo = array();
    		//将淘宝的数据地址 转化为本地的图片地址
    		foreach ( $imaglist as $image){
    			$imagetemp =(array)$image;
    			$url = $imagetemp['url'];
                $imageinfo[$i] = $this->uploadUrlPic($url);
                $i++;
    		}
    		$data['imgs']       = serialize($imageinfo);  // 数据数据  序列化存储
    		$data['user_id']    = $this->mid; 
    		$userinfo           = model('User')->getUserByIdentifier($this->mid);
    		$data['username']   = $userinfo['uname'];
    		//添加商品
    		$result = $item_mod->addGoods($data);
    		$flag = true;
    	    unset($data);
    	}
    	if ($flag){
    		$this->success("操作成功！",URL('admin/Goods/goodsList',array('status'=>'3')));
    	}else{
    		$this->success("导入失败！！",URL('admin/Goods/importGoods'));
    	}
    	 
    	}
    	
    /**
     * 搜索商品
     */
    function searchGoods(){
    	import("ORG.Util.Page"); // 导入分页类
    	if($_GET['keyword'] != null && $_GET['keyword'] != "" ){
    		$this->assign("keyword",$_GET['keyword']);
    		$this->assign("search","yes");
    	}else{
    		$this->display();
    		exit();
    	}
    	$item_site = M('item_site')->where(array('code' => 'taobao'))->find();
    	//使用淘宝开放平台API
    	vendor('Taobaotop.TopClient');
    	vendor('Taobaotop.RequestCheckUtil');
    	vendor('Taobaotop.Logger');
    	// 实例化淘宝 topclient  
    	$tb_top = new TopClient;
    	$tb_top->appkey = $item_site['appkey'];
    	$tb_top->secretKey = $item_site['secret'];
    	$req = $tb_top->load_api('ProductsSearchRequest');
    	$req->setFields('name,price,desc,pic_url,product_id');
    	$req->setQ($_GET['keyword']);
    	$pageno = empty($page->nowPage)?1:$page->nowPage;
    	$req->setPageNo($pageno);
    	$req->setPageSize(20);
        $resp = $tb_top->execute($req);
    	if (!isset($resp->products)) {
    		return false;
    	}
    	$products  = (array) $resp->products;
    	$data = (array)$products['product'];
    	foreach ($data as $k=>$v){
    		$data[$k] =(array)$data[$k];
    	}
    	$count = $resp->total_results;
    	$page = new Page($count,20);
    	$show = $page->show(); // 分页显示输出
    	$this->assign('page', $show); // 赋值分页输出
    	$this->assign('data', $data);
    	$this->display();
    }
    	
    /**
     * 批量添加商品
     */
    function batchAddGoods(){
    	if($_POST['ids'] == null || $_POST['ids'] == "" ){
    		echo 0;
    		exit();
    	}
    	$ids = explode(',', $_POST['ids']);
    	foreach ($ids as $pid){
    		$this->loadGoods2DB($pid);
    	}
    	echo  1;
    }
    
    /**
     * 根据产品id 进行入库操作
     * @param  $pid 产品id  
     */
    function  loadGoods2DB($pid){
    	if(model('Goods')->isExist($pid)){
    		return 0;
    	}
    	$item_site = M('item_site')->where(array('code' => 'taobao'))->find();
    	//使用淘宝开放平台API
    	vendor('Taobaotop.TopClient');
    	vendor('Taobaotop.RequestCheckUtil');
    	vendor('Taobaotop.Logger');
    	$tb_top = new TopClient;
    	$tb_top->appkey = $item_site['appkey'];
    	$tb_top->secretKey = $item_site['secret'];
    	$req = $tb_top->load_api('ProductGetRequest');
    	$req->setFields('name,price,desc,pic_url,product_id');
    	$req->setProductId($pid);
    	$resp = $tb_top->execute($req);
    	$item = (array)$resp->product;
    	if(empty($item)){
    		return 0;
    	}
    	// 构建商品数据
    	$data['num_iid']    = $pid;
    	$imageurl[0]        = $this->uploadUrlPic($item['pic_url']);//构建图片信息
        $data['imgs']       = serialize($imageurl);
        $data['name']       = $item['name'];
        $data['price']      = $item['price'];
        
        $data['is_del']     = 3;                                   //标记为未分类
        $data['desc']       = '未加入描述信息 ，请添加描述信息！';  
    	//$data['detail_url'] = $this->uploadUrlPic($item['detail_url']);
    	$data['user_id']    = $this->mid;
    	$userinfo           = model('User')->getUserByIdentifier($this->mid);
    	$data['username']   = $userinfo['uname'];
    	$data['created']    = time();
    	//添加商品 
    	$result = model('Goods')->addGoods($data);
    	unset($data);
    	return 1;
    	
    }
    
    /**
     * 商品分类列表
     */
    function  goodsCate(){
    	import("ORG.Util.Page"); // 导入分页类
    	$count = model('GoodsCate')->count();
    	$page = new Page($count,20);
    	$data = model('GoodsCate') -> order('id ASC ') -> limit($page->firstRow . ',' . $page->listRows)->select();
    	$show = $page->show(); // 分页显示输出
    	$this->assign('page', $show); // 赋值分页输出
    	$this->assign('data', $data);
    	$this->display();
    }
    
    /**
     * 新增商品分类显示页面
     */
    function  addGoodsCate(){
    	if(!empty($_GET['id'])){
    		$id = intval($_GET['id']);
    		$data = model('GoodsCate')->find($id);
    		$this->assign('data',$data);
    	}
    	$this->display();
    }
    
    /**
     * 新增商品分类实现
     */
    function doAddGoodsCate(){
    	if(!empty($_POST['id'])){
    		$data['id'] = intval($_POST['id']);
    	}
    	$data['name'] = $_POST['name'];
    	$result = model('GoodsCate')->addGoodsCate($data);
        if($result){
        	$this->success("操作成功",URL('admin/Goods/goodsCate'));
        }else{
        	$this->error("新增错误");
        }
    }
    
    /**
     * 删除商品分类
     */
    function doDelGoodsCate(){
    	if($_POST['ids'] == null || $_POST['ids'] == "" ){
    		echo 0;
    		exit();
    	}
    	$ids = $_POST['ids'];
    	$res = model('GoodsCate') -> where("`id` in (".$ids.")") -> delete();
    	echo $res ? 1 : 0;
    }
}